#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author       : Abmer
# @Date         : 2019-08-06 10:10:01
# @Link         : https://gitee.com/edrik
# @Modified by  : Amber
# @Modified at  : 2019-08-21 15:03:36
# @Version      : v.0.1

import ctypes
import logging
from .context import GlobalKV as gl
from .capi.mbapi import api
from .capi.mbdef import *
from .capi.mbtypes import *
from .script import *

log = logging.getLogger(__name__)

# ################################################################################
# callback


@CALLBACK(VOID, BOOL, INT, PVOID)
def wkeWindowClosingCallback(param, *args, **kwargs):
    hwnd = gl.hwnd
    log.info('[Event] Window Closing: %s %s %s' % (param, args, kwargs))

    title, head, content = 'Box', 'Are U sure to exit?', 'from callback <windowClosing>'
    try:
        button_pressed = INT()
        res = ctypes.windll.Comctl32.TaskDialog(
            hwnd,
            None,
            title,
            head,
            content,
            2 | 6 | 8,  # TDCBF_*_BUTTON *(YES|NO|CANCEL)
            65533,  # TD_INFORMATION_ICONF
            ctypes.byref(button_pressed))

        assert (res == 0)
        res = button_pressed

    except Exception as e:
        log.error(e)
        res = ctypes.windll.user32.MessageBox(hwnd, "{}\n{}".format(head, content), title, 4 | 32)

    log.info('[Event] Closing returnval: %r', res)
    # if res == 6:
    #     ctypes.windll.user32.PostMessageW(gl.hwnd, 0x010, 0, 0)  # WM_CLOSE

    return res == 6


@CALLBACK(VOID, INT, PVOID)
def wkeWindowDestroyCallback(*args):
    log.info('[Event] window destoryed: %r', args)
    ctypes.windll.user32.PostQuitMessage(0)


@CALLBACK(BOOL, INT, PVOID, INT, PVOID)
def wkeNavigationCallback(webview, param, navigation_type, url_p):

    log.info('[Event] Navigation %r %r %r %r', webview, param, navigation_type, url_p)
    p = api.wkeGetStringW(url_p)
    # log.info('url_p:', p, PWCHAR(url_p).value)
    # url = PWCHAR(p).value # fail
    url = PWCHAR(p).value  # ?
    msg = '[Event] webview navigate: %s | triggerType: %s' % (url, navigation_type)
    log.info(msg)
    return True


@CALLBACK(VOID, HWND, PVOID)
def wkeDidCreateScriptContextCallback(webview, *args):
    log.info("[Event] create script context")
    pass


@CALLBACK(BOOL, HWND, PVOID, PUTF8, PVOID)
def wkeLoadUrlBeginCallback(webview, param, purl, pjob):
    log.info('[Event] load url begin %r %r %r %r', webview, param, purl, pjob)
    # api.wkeNetSetHTTPHeaderField(job, key, value, response)
    # api.wkeNetSetMIMEType(job, type)
    # api.wkeNetCancelRequest(job)

    return True


@CALLBACK(BOOL, HWND, PVOID, PUTF8, PVOID)
def wkeLoadUrlEndCallback(webview, param, purl, pjob):
    log.info('[Event] load url end %r %r %r %r', webview, param, purl, pjob)
    # api.wkeNetSetData(job, buf, len)
    return True


@CALLBACK(BOOL, HWND, PVOID, PUTF8, PVOID)
def wkeLoadingFinishCallback(webview, param, purl, pjob):
    log.info('[Event] loading finish ')
    return True


@CALLBACK(WCHAR, PVOID)
def wkeString(p_str):
    return PWCHAR(api.wkeGetStringW(p_str)).value


@CALLBACK(VOID, INT, PVOID, PVOID)
def wkeTitleChangedCallback(webview, param, p_title):
    log.info(p_title)
    title = PWCHAR(api.wkeGetStringW(p_title)).value

    log.info('[Event] webview title changed: %s', title)
    title = 'PyMiniblink - %s' % title
    log.info('[Reset] reset title: %s', title)
    api.wkeSetWindowTitleW(webview, title)


@CALLBACK(VOID, HWND, HWND, PVOID)
def wkeDocumentReady2Callback(webview, frame, param):
    log.info('[Event] DocumentReady2 %r %r %r', webview, frame, param)

    # calljs
    """
    绑定js：主要是跟h5页面联调，定好接口:
    C++ 调用js(wkeJsBindFunction),
    js调用C++(wkeRunJsByFrame)。使用起来还是挺方便的。
    """
    run_js('console.log("doc ready")')


@CALLBACK(VOID, INT, PVOID)
def wkeDocumentReadyCallback(webview, param):
    msg = '[Event] Document Ready.'
    log.info(msg)


@CALLBACK(VOID, INT, PVOID, PVOID, PVOID)
def wkeCreateViewCallback(webview, param, navigation_type, p_url, window_features):
    msg = "[Event] CreateView"
    log.info(msg)
